<template>
<div class="bas">
 <el-container style="height: 1000px; border: 1px solid #eee">
  <el-aside width="200px" style="background-color: #304156">
    
    <el-menu default-active="1-4-1" 
      class="el-menu-vertical-demo" 
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#ffd04b"
      router
    >
        <!-- 导航菜单 -->
        <el-submenu v-for="(item,index) in menuList" :key="index" :index="item.mid+''">
         <template slot="title">
            <i :class="item.mioc"></i>
            <span>{{item.remark}}</span>
          </template>
        <el-menu-item-group>
           <el-menu-item v-for="child in item.children" :key="child.mid" :index='child.murl'>{{child.remark}}</el-menu-item>
        </el-menu-item-group>
      </el-submenu>
      

    </el-menu>
  </el-aside>
  <!-- 右侧头部 -->
  <el-container>
    <el-header style="text-align: right; font-size: 12px">

      <el-menu :default-active="activeIndex"  class="el-menu-demo" mode="horizontal" @select="handleSelect">
        <!-- <el-menu-item index="1">处理中心</el-menu-item>
        <el-menu-item index="2" >工作台</el-menu-item>
        <el-menu-item index="3" >消息中心</el-menu-item> -->
        <el-menu-item index="4" style="float:right"> 
          <el-dropdown>
    
            <el-col :span="12">
            <div class="photo">
            <el-avatar fit="fill" :src="require('D://img//'+photoUrl)"></el-avatar>
            </div>
            </el-col> 
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item  @click.native="geren">个人信息</el-dropdown-item>
              <el-dropdown-item><a href="/logout">退出登录</a></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <span v-text="uname"></span>
        </el-menu-item>
      </el-menu>
     
    </el-header>
     <div class="app-wrap">
            <!-- 此处放置el-tabs代码 -->
            <div >
              <el-tabs
                v-model="activeIndex"
                type="border-card"
                closable
                v-if="openTab.length"
                @tab-click='tabClick'
                @tab-remove='tabRemove'
                >
                <el-tab-pane
                  v-for="item in openTab"
                  :key="item.name"
                  :label="item.name"
                  :name="item.route"
                 >
                 
                </el-tab-pane>
              </el-tabs>
              <div>
                   <router-view></router-view>
                </div>
            </div>
     </div>

  </el-container>
</el-container>

<!-- 修改密码 -->
<el-dialog
  :visible.sync="dialogVisible"
  width="40%"
  :before-close="handleClose">
  <el-tabs tab-position="left" style="height: 500px;">
    <!-- 修改个人信息 -->
    <el-tab-pane class="tab"  label="个人信息">
      <el-form :model="form">
      <el-form-item label="序号" :label-width="formLabelWidth" hidden>
        <el-input hidden v-model="form.uid" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="姓名" :label-width="formLabelWidth">
        <el-input v-model="form.uname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="账户" :label-width="formLabelWidth">
        <el-input v-model="form.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机号" :label-width="formLabelWidth">
        <el-input v-model="form.phone" autocomplete="off"></el-input>
      </el-form-item>
       <el-form-item label="性别" :label-width="formLabelWidth">
         <el-radio-group v-model="form.sex">
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="生日" :label-width="formLabelWidth">
         <el-date-picker type="date" placeholder="选择日期" v-model="form.birthday" style="width: 100%;"></el-date-picker>
      </el-form-item>
      <el-button type="primary" style="float:right;margin-right:30px" @click="submit()" >确 定</el-button>
    </el-form>
    
    </el-tab-pane>
    <!-- 修改头像 -->
    <el-tab-pane class="tab" label="修改头像">
<!-- 上传单个图片 -->
<div>
    <h2 style="margin-bottom:10px">上传单个图片</h2>
    <el-upload
        class="avatar-uploader"
        action="/"
        name="head"
        multiple 
        :headers="headers"
        list-type="picture-card"
        :on-change="uploadFile"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :http-request="httpRequest"
        :class="{'demo-httpRequestImg':httpRequestImg}"
        >
        <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisibleImg" append-to-body class="ImgClass">
        <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <div slot="footer" class="dialog-footer" style="float:right;padding:20px,50px;margin-top:30px">
      <el-button type="primary" @click="dialogVisible = false,submitForm()">开始上传</el-button>      
      <!--  -->
    </div>
  </div>

<!-- 修改密码 -->
    </el-tab-pane>
    <el-tab-pane class="tab" label="修改密码">
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="序号" :label-width="formLabelWidth" hidden>
            <el-input hidden v-model="form.uid" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePass('ruleForm')">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
      </el-form>
    </el-tab-pane>
  </el-tabs>
  <!-- <span slot="footer" class="dialog-footer">
    <el-button  @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span> -->
</el-dialog>
</div>
   
</template>
<style lang="scss" scoped>
  .demo-httpRequestImg{
    /deep/ .el-upload--picture-card{
        display: none;
    }
  } 
</style>
<style  scoped>
  .el-header {
    background-color: #ffffff;
    color: #333;
    line-height: 60px;
           
  }
  .el-aside {
    color: #333;
  }
</style>

<script>
import axios from "axios"
  export default {
    data() {
      // console.log("authUser--",this.$qs.parse(sessionStorage.getItem("authUser")))
      // console.log("authUser2--",this.$store.state.token)
       var validatePass = (rule, value, callback) => {
        if (value === '' && value.length>=3) {
          callback(new Error('密码格式不正确'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '' && value.length>=3) {
          callback(new Error('密码格式不正确'));
        } else if (value !== this.ruleForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
          photoUrl:"",
          menuList:[],
          uname:"",
          dialogVisible:false,
          formLabelWidth:"80px",
          // 图片上传
          imgUrl :"",
          dialogImageUrl: '',//预览url
          dialogVisibleImg:false,
          httpRequestImg:false,//展示单个图片
          // 图片上传结束
          form:{},
          ruleForm: {
            pass: '',
            checkPass: '',
            age: ''
          },
          rules: {
            pass: [{ validator: validatePass, trigger: 'blur' }],
            checkPass: [{ validator: validatePass2, trigger: 'blur' }],
          }
      }
    },created(){
        let authUser=this.$qs.parse(sessionStorage.getItem("authUser"))
        this.uname=authUser.uname;
        this.photoUrl=authUser.photo
        console.log(this.photoUrl)
        this.$http.get('admin/finByRid',{params:{rid:authUser.rid}}).then(res=>{
           this.menuList=res
        })
      
      //  console.log("rid----"+)
    },
 methods: {
   geren(){
     let authUser=this.$qs.parse(sessionStorage.getItem("authUser"))
     console.log(authUser)
     this.form=authUser
     console.log(this.form)
     this.dialogVisible = true  
   },
  //  修改个人信息
   submit(){
     console.log(this.form)
     this.$http.get("/admin/geren",{params:{...this.form}}).then(res=>{
       if(res){
         this.$message("修改个人信息成功")
       }
     })
   },
    //修改密码 
   updatePass(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let authUser=this.$qs.parse(sessionStorage.getItem("authUser"))

            this.$http.get("/admin/updatePass",{params:{uid:authUser.uid,pwd:this.ruleForm.pass}}).then(res=>{
              if(res){
                window.location.href = '/logout';
              }else{
                this.$$message("修改失败")
              }
            })
            this.$message(authUser.uid+"---------"+this.ruleForm.pass)
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
  //  修改头像
   uploadFile(file) {
      this.imgUrl = file.raw // 拿到文件的信息
   },
    httpRequest(a) { //上传成功
      this.httpRequestImg = true;
      
    },
    handlePictureCardPreview(file) { //预览
      this.dialogImageUrl = file.url;
      this.dialogVisibleImg = true;
    },
    handleRemove(file, fileList) { //删除
      this.httpRequestImg = false;
      console.log(file, fileList);
    },
    submitForm() {
      let formdata = new FormData()
      formdata.append("head", this.imgUrl)
       let authUser=this.$qs.parse(sessionStorage.getItem("authUser"))
      formdata.append("uid", authUser.uid)
      axios({
        method: 'post',
        url: 'http://localhost:8090/admin/upload',
        data:formdata,
        headers: {
          "Authorization":sessionStorage.getItem("token"),
          'Content-Type': 'multipart/form-data'
        }
      }).then(res=>{
        console.log(res)
        this.dialogVisible=false
        location.reload()
      })
    },
  //  修改密码
   handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      // 头部标签页
      handleSelect(key, keyPath) {
        console.log(key, keyPath);
      },
      //tab标签点击时，切换相应的路由
    tabClick(tab){
      console.log("tab",tab);
      console.log('active',this.activeIndex);
      this.$router.push({path: this.activeIndex});
    },
    //移除tab标签
    tabRemove(targetName){
      console.log("tabRemove",targetName);
      // 首页不删
     if(targetName == '/'||targetName == '/admin/welcome'){
        return
      }
      this.$store.commit('delete_tabs', targetName);
      if (this.activeIndex === targetName) {
     
        // 设置当前激活的路由
        if (this.openTab && this.openTab.length >= 1) {
          console.log('=============',this.openTab[this.openTab.length-1].route)
          this.$store.commit('set_active_index', this.openTab[this.openTab.length-1].route);
          this.$router.push({path: this.activeIndex});
        }
         else {
          this.$router.push({path: '/admin/welcome'});
        }
      }
    }
    },
    mounted  () {
    // 刷新时以当前路由做为tab加入tabs
    // 当前路由不是首页时，添加首页以及另一页到store里，并设置激活状态
    // 当当前路由是首页时，添加首页到store，并设置激活状态

    if (this.$route.path !== '/admin' && this.$route.path !== '/admin/welcome') {
      this.$store.commit('add_tabs', {route: '/admin/welcome' , name: 'Welcome'});
      this.$store.commit('add_tabs', {route: this.$route.path , name: this.$route.name });
      this.$store.commit('set_active_index', this.$route.path);
    } else {
      this.$store.commit('add_tabs', {route: '/admin/welcome', name: 'Welcome'});
      this.$store.commit('set_active_index', '/admin/welcome');
      this.$router.push('/admin/welcome');
    }

  },
  computed: {
    openTab () {
      return this.$store.state.openTab;
    },
    headers() {
        return{
        "Authorization":sessionStorage.getItem("token"),
        'Content-Type': 'multipart/form-data'
        }
    },
    activeIndex:{
      get () {
        return this.$store.state.activeIndex;
      },
      set (val) {
        this.$store.commit('set_active_index', val);
      }
    }
  },
  watch:{
    '$route'(to,from){
        //判断路由是否已经打开
        //已经打开的 ，将其置为active
        //未打开的，将其放入队列里
        let flag = false;
        
        for(let item of this.openTab){
          console.log("item.name",item.name)
          console.log("t0.name",to.name)

          if(item.name === to.name){
            console.log('to.path--这个是已有',to.path);
            this.$store.commit('set_active_index',to.path)
            flag = true;
            break;
          }
        }

        if(!flag){
          console.log('to.pat--添加h',to.path);
          this.$store.commit('add_tabs', {route: to.path, name: to.name});
          this.$store.commit('set_active_index', to.path);
        }

    }
  }

    
  };
</script>
<style scoped>
.el-col{
  padding: 0 10px;
}
</style>